package zouhaotian.rbac.dao.file;

import zouhaotian.rbac.dao.IBaseDao;
import zouhaotian.rbac.domain.entity.BaseEntity;

import java.util.*;

/**
 * 数据访问层基类
 *
 * @auther 邹昊天
 * @since 2025/6/21 20:20
 */
abstract class BaseDao<Entity extends BaseEntity> implements IBaseDao<Entity> {

    Class<Entity> clazz;

    private int idCounter;

    void init(){
        List<String> fileName = PersistUtil.listFileNames(clazz);
        int maxId=fileName.stream().mapToInt(Integer::parseInt).max().orElse(0);
        idCounter =maxId+1;
    }

    @Override
    public Collection<Entity> list() {
        return PersistUtil.listAll(clazz);
    }

    @Override
    public boolean existsById(int id) {
        return PersistUtil.exists(clazz, id);
    }

    @Override
    public Entity findById(int id) {
        return PersistUtil.read(clazz ,id);
    }

    @Override
    public Entity save(Entity entity) {
        Integer id = entity.getId();
        if (id == null){
            id = idCounter++;
            entity.setId(id);
        }
        PersistUtil.write(entity);
        return entity;
    }

    @Override
    public Entity delete(int id) {
        Entity entity = PersistUtil.read(clazz, id);
        PersistUtil.delete(clazz, id);
        return entity;
    }
}
